#!/usr/bin/python
############################################################################
# Copyright (C) 2010-2011 Mkhanyisi Madlavana <mmadlavana@gmail.com>
#
# This program is free software; you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation; either version 2 of the License, or
# (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program; if not, write to the Free Software
# Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
############################################################################

import sys
import os
from optparse import OptionParser as op

import mutagen
import mutagen.id3 as id3
import mutagen.mp3 as mp3
import mutagen.asf as wma
import mutagen.mp4 as aac
import mutagen.oggvorbis as ogg

parser = op(usage="%prog [OPTIONS] files", version="v1.0.1")
parser.add_option('-t', '--title')
parser.add_option('-a', '--artist')
parser.add_option('-A', '--album')
parser.add_option('-T', '--tracknumber')
parser.add_option('-g',	'--genre')
parser.add_option('-y',	'--year')
parser.add_option('-l', '--list_tags')
opts, files = parser.parse_args()

def setmetadata(files):
	global mytags
	for f in files:
		if f.lower().endswith('.mp3'):
			metadata = mp3.Open(f)
			tags = {}
			if mytags['artist'] is not None:
				tags['TPE1'] = id3.TPE1(encoding=3, text=[u'%s' % mytags['artist']])
			if mytags['title'] is not None:
				tags['TIT2'] = id3.TIT2(encoding=3, text=[u'%s' % mytags['title']])
			if mytags['album'] is not None:
				tags['TALB'] = id3.TALB(encoding=3, text=[u'%s' % mytags['album']])
			if mytags['date'] is not None:
				tags['TDRC'] = id3.TDRC(encoding=3, text=[u'%s' % mytags['date']])
			if mytags['genre'] is not None:
				tags['TCON'] = id3.TCON(encoding=3, text=[u'%s' % mytags['genre']])
			if mytags['tracknumber'] is not None:
				tags['TRCK'] = id3.TRCK(encoding=3, text=[u'%s' % mytags['tracknumber']])

		elif f.lower().endswith('.wma'):
			metadata = wma.Open(f)
			tags = {}
			if mytags['title'] is not None:
				tags["Title"] = mytags['title']
			if mytags['artist'] is not None:
				tags["Author"] = mytags['artist']
			if mytags['album'] is not None:
				tags["WM/AlbumTitle"] = mytags['album']
			if mytags['date'] is not None:
				tags["WM/Year"] = mytags['date']
			if mytags['genre'] is not None:
				tags["WM/Genre"] = mytags['genre']
			if mytags['tracknumber'] is not None:
				tags["WM/TrackNumber"] = mytags['tracknumber']

		elif f.lower().endswith('.ogg'):
			metadata = ogg.Open(f)
			tags = {}
			for key, value in mytags.items():
				if value is not None:
					tags[key] = value

		elif f.lower().endswith('.m4a') or f.lower().endswith('.aac') or f.lower().endswith('.mp4'):
			metadata = aac.Open(f)
			tags = {}
			if mytags['title'] is not None:
				tags['\xa9nam'] = [u'%s' % mytags['title']]
			if mytags['artist'] is not None:
				tags['\xa9ART'] = [u'%s' % mytags['artist']]
			if mytags['album'] is not None:
				tags['\xa9alb'] = [u'%s' % mytags['album']]
			if mytags['genre'] is not None:
				tags['\xa9gen'] = [u'%s' % mytags['genre']]
			if mytags['date'] is not None:
				tags['\xa9day'] = [u'%s' % mytags['date']]
			if mytags['tracknumber'] is not None:
				tags['trkn'] = [(int(mytags['tracknumber'].split('/')[0]), 0)]
		else:
			print f, "not supported yet"
			continue

		for key, value in tags.items():
			if value is not None:
				metadata[key] = value
		metadata.save()

def getmetadata(files):
	for f in files:
		a = None
		A = None
		t = None
		g = None
		y = None
		T = None
		m = mutagen.File(f)

		if f.lower().endswith('.ogg'):
			if m.has_key('artist'):
				a = 'ARTIST=' + m['artist'][0].encode('utf-8')
			if m.has_key('album'):
				A = 'ALBUM=' + m['album'][0]
			if m.has_key('title'):
				t = 'TITLE=' + m['title'][0]
			if m.has_key('genre'):
				g = 'GENRE=' + m['genre'][0]
			if m.has_key('date'):
				y = 'YEAR=' + m['date'][0]
			if m.has_key('tracknumber'):
				T = 'TRACKNUMBER=' + m['tracknumber'][0]

		elif f.lower().endswith('.mp3'):
			if m.has_key('TPE1'):
				a = 'ARTIST=' + str(m['TPE1'])
			if m.has_key('TALB'):
				A = 'ALBUM=' + str(m['TALB'])
			if m.has_key('TIT2'):
				t = 'TITLE=' + str(m['TIT2'])
			if m.has_key('TCON'):
				g = 'GENRE=' + str(m['TCON'])
			if m.has_key('TDRC'):
				y = 'YEAR=' + str(m['TDRC'])
			if m.has_key('TRCK'):
				T = 'TRACKNUMBER=' + str(m['TRCK'])

		elif f.lower().endswith('.wma'):
			if m.has_key('Author'):
				a = 'ARTIST=' + m['Author'][0]
			if m.has_key('WM/AlbumTitle'):
				A = 'ALBUM=' + str(m['WM/AlbumTitle'][0])
			if m.has_key('Title'):
				t = 'TITLE=' + m['Title'][0]
			if m.has_key('WM/Genre'):
				g = 'GENRE=' + str(m['WM/Genre'][0])
			if m.has_key('TRCK'):
				y = 'YEAR=' + str(m['WM/Year'][0])
			if m.has_key('WM/TrackNumber'):
				T = 'TRACKNUMBER=' + str(m['WM/TrackNumber'][0])

		elif f.lower().endswith('.m4a') or f.lower().endswith('.aac') or f.lower().endswith('.mp4'):
			if m.has_key('\xa9ART'):
				a = 'ARTIST=' + m['\xa9ART'][0]
			if m.has_key('\xa9alb'):
				A = 'ALBUM=' + m['\xa9alb'][0]
			if m.has_key('\xa9nam'):
				t = 'TITLE=' + m['\xa9nam'][0]
			if m.has_key('\xa9gen'):
				g = 'GENRE=' + m['\xa9gen'][0]
			if m.has_key('\xa9day'):
				y = 'YEAR=' + m['\xa9day'][0]
			if m.has_key('trkn'):
				T = 'TRACKNUMBER=' + str(m['trkn'][0][0])
	
		print "--- %s" % f
		if t is not None:
			print t
		if a is not None:
			print a
		if A is not None:
			print A
		if T is not None:
			print T
		if g is not None:
			print g
		if y is not None:
			print y
		print ""

if opts.list_tags is not None:
	getmetadata(files)
else:
	mytags={}
	mytags['title'] = opts.title
	mytags['artist'] = opts.artist
	mytags['album'] = opts.album
	mytags['date'] = opts.year
	mytags['genre'] = opts.genre
	mytags['tracknumber'] = opts.tracknumber
	setmetadata(files)

